﻿/// <reference path="../base.js" />
/// <reference path="./window.js" />
/// <reference path="../3rdParty/Mootools-Core.js" />
/// <reference path="../3rdParty/Mootools-More.js" />
/// <reference path="../3rdParty/Clientcide.js" />

/* SelectSectorWindow
 *
 * Init()
 * Show()
 * Hide()
 * Select()
 */

SelectSectorWindow = {};

SelectSectorWindow.Init = function()
{
  var content = "<h3>Choose a Sector</h3>"
              + "<form id='SelectSectorForm'>"
              + "<span>Name: </span><input type='text' id='SelectSectorName' class='required minLength:3 maxLength:30 alphanum' maxlength='30' /><br />"
              + "<select id='SelectSectorSelect' size='8'>"
              + "</select><br />"
              + "<span>Filter: </span><input type='text' id='SelectSectorFilter' onkeyup='SelectSectorWindow.Filter();' /><br /><br />"
              + "<input type='button' value='Select' onclick='SelectSectorWindow.Select();'>"
              + "</form>";

  SelectSectorWindow.Window = new UIWindow({ name: "SelectSectorWindow",
    caption: "Select Sector",
    content: content,
    modal: true
  });

  SelectSectorWindow.Validator = new Form.Validator.Tips($("SelectSectorForm"), { scrollToErrorsOnSubmit: false });
}

SelectSectorWindow.Show = function(callback)
{
  if (!SelectSectorWindow.Window)
    SelectSectorWindow.Init();

  SelectSectorWindow.Window.show();
  $("SelectSectorFilter").set("value", "");
  SelectSectorWindow.Filter();
  SelectSectorWindow.Callback = callback;
}

SelectSectorWindow.Hide = function()
{
  SelectSectorWindow.Window.hide();
}

SelectSectorWindow.Filter = function()
{
  var select = $("SelectSectorSelect");
  select.empty();
  var term = $("SelectSectorFilter").get("value").toLowerCase();

  var sectors = $A(Global.SectorNames);
  sectors.sort();

  for (var i = 0; i < sectors.length; i++)
  {
    if(sectors[i].toLowerCase().search(term) != -1)
      (new Element("option", { value: sectors[i], html: sectors[i] })).addEvent("click", function(){ $("SelectSectorName").set("value", this.value); }).inject(select, "bottom");
  }
}

SelectSectorWindow.Select = function()
{
  if (!$chk($("SelectSectorSelect").getSelected()) || !SelectSectorWindow.Validator.validate())
    return;

  var sector = $("SelectSectorSelect").getSelected()[0].get("value");

  Utility.Server.GetSectorCode(sector, (function(result)
  {
    if (result == false)
    {
      new UIWindow({ caption: "Error", content: "Sector not found in database." }).show();
    }
    else
    {
      var sector = new Sector(this.name, [], [], [], [], Global.CachedSectors[this.sector], this.sector, new Pricelist("", [], []));
      SelectSectorWindow.Callback(sector);
    }

    SelectSectorWindow.Hide();
  }).bind({ sector: sector, name: $("SelectSectorName").get("value") }));
}